import { ref, reactive, markRaw } from 'vue';
import { removeUndefinedParams } from '@/utils/index';
import type { SearchOptionsType, TableFieldsSettingType } from '@/components/CPageTable';
import { CarbonInventoryStandardsOption } from '@/constants/enum';
import { getListEmissionTask, getListEmissionData } from '@/apis/eci/emissionAccounting/detail';
import type { GetListEmissionTaskResult } from '@/apis/eci/emissionAccounting/model/detailModel';

interface SearchListFillTaskType extends GetListEmissionTaskResult {
  label: string;
  value: any;
}

export const useDetail = (onSearchFormCodeChange: (list: GetListEmissionTaskResult[]) => void) => {
  // 搜索字段及其他
  const searchForm = reactive({
    organizationCode: '',
    organizationName: '',
    inventoryYear: '',
    standard: ''
  });

  /**
   * 接口返回的全量的入参列表（处理过字段名称了）
   */
  const apiResParamsList = ref<SearchListFillTaskType[]>([]);
  /**
   * 显示在页面上的入参列表
   */
  const pageShowParamsList = ref<SearchListFillTaskType[]>([]);
  // 搜索配置
  const searchOptions: SearchOptionsType[] = markRaw([
    {
      name: '组织名称',
      placeholder: '组织名称',
      field: 'organizationCode',
      type: 'select',
      allowClear: false,
      remoteMethod: async (query: string): Promise<LabelValueOptions> => {
        try {
          // 没有获取过列表或者列表为空，请求接口
          if (!apiResParamsList.value?.length) {
            const res = await getListEmissionTask();
            apiResParamsList.value = handleListParamsFormat(res);
          }
          // 有搜索入参的
          if (query && query.trim()) {
            pageShowParamsList.value = handleQueryListParams(query, apiResParamsList.value);
          } else {
            pageShowParamsList.value = apiResParamsList.value;
          }
          return Promise.resolve(pageShowParamsList.value);
        } catch (error) {
          console.log('error', error);
          apiResParamsList.value = [];
          pageShowParamsList.value = [];
          return Promise.resolve(pageShowParamsList.value);
        }
      },
      onSearchFormChange: () => onSearchFormCodeChange(pageShowParamsList.value)
    },
    {
      name: '盘查周期',
      field: 'inventoryYear',
      allowClear: false,
      type: 'select',
      disabled: true,
      options: []
    },
    {
      name: '核算标准',
      field: 'standard',
      type: 'select',
      allowClear: false,
      options: CarbonInventoryStandardsOption
    }
  ]);

  let spanEmissionScope: number[] = [];
  let spanEmissionCategory: number[] = [];
  const posSpanEmissionScope = ref(0); // 范围
  const posSpanEmissionCategory = ref(0); // 类型
  const cellMerge = ({ column, rowIndex, columnIndex }: any) => {
    if (column.title == '范围' || column.title == '温室气体源类型') {
      if (columnIndex === 0) {
        const _row = spanEmissionScope[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
      if (columnIndex === 1) {
        const _row = spanEmissionCategory[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    }
  };
  const getSpanArr = (data: any) => {
    spanEmissionScope = [];
    spanEmissionCategory = [];
    for (let i = 0; i < data.length; i++) {
      if (i === 0) {
        spanEmissionScope.push(1);
        posSpanEmissionScope.value = 0;
      } else {
        // 判断当前元素与上一个元素是否相同
        if (data[i].emissionScope === data[i - 1].emissionScope) {
          spanEmissionScope[posSpanEmissionScope.value] += 1;
          spanEmissionScope.push(0);
        } else {
          spanEmissionScope.push(1);
          posSpanEmissionScope.value = i;
        }
      }

      if (i === 0) {
        spanEmissionCategory.push(1);
        posSpanEmissionCategory.value = 0;
      } else {
        // 判断当前元素与上一个元素是否相同
        if (
          data[i].ghgSourceName === data[i - 1].ghgSourceName &&
          data[i].emissionScope === data[i - 1].emissionScope
        ) {
          spanEmissionCategory[posSpanEmissionCategory.value] += 1;
          spanEmissionCategory.push(0);
        } else {
          spanEmissionCategory.push(1);
          posSpanEmissionCategory.value = i;
        }
      }
    }
  };
  const addTdClass = ({ column }: any) => {
    if (column.title == '范围') {
      return 'merged-cell';
    } else if (column.title == '温室气体源类型') {
      return 'merged-cell';
    }
  };

  const tableOptions = {
    pagination: false,
    immediate: false,
    loadData,
    border: true,
    extraTableOption: {
      spanMethod: cellMerge,
      cellClassName: addTdClass
    }
  };

  async function loadData(): Promise<any> {
    // 如果参数不全，则列表为空
    if (!searchForm.organizationCode || !searchForm.inventoryYear || !searchForm.standard) {
      return Promise.resolve({
        records: [],
        total: 0
      });
    }
    const params = handleParams();
    return getListEmissionData(params).then(res => {
      if (res && res.length) {
        getSpanArr(res);
        return {
          records: res,
          total: res.length
        };
      } else {
        return {
          records: [],
          total: 0
        };
      }
    });
  }

  // 处理参数
  const handleParams = () => {
    // 参数
    let params = {
      organizationCode: searchForm.organizationCode,
      dataPeriod: searchForm.inventoryYear,
      standard: searchForm.standard,
      organizationName: searchForm.organizationName
    };
    params = removeUndefinedParams(params);
    return params;
  };

  const tableFieldsSetting: TableFieldsSettingType[] = [
    {
      title: '范围',
      field: 'emissionScope',
      columnSettingConfig: {
        enabled: true
      }
    },
    {
      title: '温室气体源类型',
      field: 'ghgSourceName',
      columnSettingConfig: {
        enabled: true
      }
    },
    {
      title: '排放源',
      field: 'sourceName',
      columnSettingConfig: {
        enabled: true
      }
    },
    {
      title: '燃料/能源/物料',
      field: 'materialName',
      columnSettingConfig: {
        enabled: true
      }
    },
    {
      title: '碳排放值',
      field: 'activityData',
      align: 'right',
      columnSettingConfig: {
        enabled: true
      }
    },
    {
      title: '单位',
      field: 'unit',
      minWidth: '100',
      columnSettingConfig: {
        enabled: true
      }
    }
  ];

  return {
    searchForm,
    searchOptions,
    tableOptions,
    handleParams,
    tableFieldsSetting
  };
};

/**
 * 处理接口返回的数据列表
 * @param res
 * @returns
 */
function handleListParamsFormat(res: GetListEmissionTaskResult[]) {
  const list: SearchListFillTaskType[] = [];
  for (let i = 0; i < res.length; i++) {
    const item = res[i];
    list.push({
      label: item.organizationName,
      value: item.organizationCode,
      ...item
    });
  }
  return list;
}

/**
 * 前端搜索功能
 * @param query
 * @param list
 * @returns
 */
function handleQueryListParams(query: string, list: SearchListFillTaskType[]) {
  const res: SearchListFillTaskType[] = [];
  list?.forEach(item => {
    if (item.organizationName.toLocaleLowerCase().indexOf(query.toLocaleLowerCase()) > -1) {
      res.push({
        ...item
      });
    }
  });
  return res;
}
